<?php
namespace hema\device\engine;

/**
 * 飞鹅打印机驱动引擎
 * 测试机型号：FP-V58W
 */
class Feieyun extends Basics
{
    /**
     * 构造方法
     */
    public function __construct($dev_type, $device, $data, $tpl)
    {
        parent::__construct($dev_type, $device, $data, $tpl);
    }

    /**
    * [打印订单接口 Open_printMsg]
    */
    public function print()
    {
        if($this->tpl == 0){
            $content = $this->make_order_templet($this->data);//制作订单模板
        }else{
            $content = $this->make_refund_templet($this->data);//制作退单模板
        }
        $msgInfo = $this->msgInfo();
        $msgInfo['apiname'] = 'Open_printMsg';
        $msgInfo['sn'] = $this->device['dev_id'];
        $msgInfo['content'] = $content;
        $msgInfo['times'] = $this->device['values']['prt_num'];
        $result = json_decode($this->http_post_json($msgInfo),true);
        return true;
    }
    
    /**
    * [获取某台打印机状态接口 Open_queryPrinterStatus]
    */
    public function status(){
        $msgInfo = $this->msgInfo();
        $msgInfo['apiname'] = 'Open_queryPrinterStatus';
        $msgInfo['sn'] = $this->data['dev_id'];
        $res = json_decode($this->http_post_json($msgInfo),true);
        if($res['ret']==0){
            $msg = '离线';
            if($res['data']=='在线，工作状态正常。'){
                $msg = '正常';
            }
            if($res['data']=='在线，工作状态不正常。'){
                $msg = '异常';
            }
            return $msg;
        }
        return '未知';
    }
    
    /**
    * [批量添加打印机接口 Open_printerAddlist]
    */
    public function add()
    {
        $data = $this->data;
        //$printerContent,编号(必填) # 打印机识别码(必填) # 备注名称(选填) # 流量卡号码(选填)
        $printerContent = $data['dev_id'] . '#' . $data['dev_key'].'#'. $data['dev_name'];
        $msgInfo = $this->msgInfo();
        $msgInfo['apiname'] = 'Open_printerAddlist';
        $msgInfo['printerContent'] = $printerContent;
        $result = json_decode($this->http_post_json($msgInfo),true);
        if($result['ret']!=0){
            $this->error = $result['msg'];
            return false;
        }
        return $result;
    }
    
    /**
    * [批量删除打印机 Open_printerDelList]
    * @param  [string] $snlist [打印机编号，多台打印机请用减号“-”连接起来]
    * @return [string]         [接口返回值]
    */
    public function delete(){
        $msgInfo = $this->msgInfo();
        $msgInfo['apiname'] = 'Open_printerDelList';
        $msgInfo['snlist'] = $this->data['dev_id'];
        $result = json_decode($this->http_post_json($msgInfo),true);
        if($result['ret']!=0){
            $this->error = $result['msg'];
            return false;
        }
        return $result;
    }

    public function getToken()
    {

    }
    public function edit()
    {
        
    }
    public function push()
    {
        
    }

    /**
    * 公共参数
    */
    private function msgInfo(){
        $time = time();         //请求时间
        return $msgInfo = [
            'user'=>$this->config['app_key'],
            'stime'=>$time,
            'sig'=>$this->signature($time)
        ];
    }
    
    /**
    * [signature 生成签名]
    */
    private function signature($time){
        return sha1($this->config['app_key'] . $this->config['app_secret'] . $time);//公共参数，请求公钥
    }
    
    /**
     * 发送post请求
     * PHP发送Json对象数据
     */
    private function http_post_json($data)
    {
        $data = http_build_query($data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $this->config['api_url']);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/x-www-form-urlencoded',
                'Content-Length: ' . strlen($data)
            )
        );
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $response;
    }
    
    /**
     * 制作订单模板
     * $data 订单数据
     * 58mm的机器,一行打印16个汉字,32个字母;
     */
    private function make_order_templet($data)
    {
        /*
         <BR> ：换行符
         <CUT> ：切刀指令(主动切纸,仅限切刀打印机使用才有效果) 
         <LOGO> ：打印LOGO指令(前提是预先在机器内置LOGO图片)
         <PLUGIN> ：钱箱或者外置音响指令
         <CB></CB>：居中放大
         <B></B>：放大一倍
         <C></C>：居中
         <L></L>：字体变高一倍
         <W></W>：字体变宽一倍
         <QR></QR>：二维码（单个订单，最多只能打印一个二维码）
         <RIGHT></RIGHT>：右对齐
         <BOLD></BOLD>：字体加粗
        */
        if($data['order_mode']['value']==10){
            if(isset($data['table']['table_name'])){
                $title = $data['table']['table_name'];
            }else{
                $title = '堂食'.$data['row_no'].'号';
            }
        }
        if($data['order_mode']['value']==20){
            $title = '外卖'.$data['row_no'].'号';
        }
        if($data['order_mode']['value']==30){
            $title = '自取'.$data['row_no'].'号';
        }
        $content = '<CB># '.$title.' #</CB><BR>';
        if($data['arrive_time']['value']>0){
            $content .= '到店时间:'.$data['arrive_time']['text'].'<BR>';
        }
        $content .= '--------------------------------<BR>';
        $content .= '<C>'.$data['shop']['shop_name'].'</C><BR>';
        if($data['pay_status']['value'] != 30){
            if($data['transaction_id']){
                $content .= '<C>-- 微信支付 --</C><BR>';
            }else{
                $content .= '<C>-- 余额支付 --</C><BR>';
            }
            $content .= '支付时间:'.datetime($data['pay_time']).'<BR>';
        }else{
            $content .= '<C>-- 后付款 --</C><BR>';
        }
        $content .= '<B>名称        数量</B><BR>';//字符占位数量4+8+4
        $content .= '--------------------------------<BR>';
        //循环拼接打印模板
        for ($i = 0; $i < sizeof($data['goods']); $i++) {
                $goods_name = $data['goods'][$i]['goods_name'];//产品名字
                !empty($data['goods'][$i]['goods_attr']) && $goods_name .= "/" . $data['goods'][$i]['goods_attr'];
                $total_num = $data['goods'][$i]['total_num'];   //产品数量
                //设置名称字符长度
                $lan = mb_strlen($goods_name,'utf-8')*2;//一个汉字2个字符长度
                for($n=$lan;$n<13;$n++){
                    $goods_name .= ' ';
                }
                $content .= '<B>' . $goods_name . '×' .$total_num . '</B><BR>';
        }
        $content .= '--------------------------------<BR>';
        $content .= '商品金额：+￥'.$data['total_price'].'<BR>';
        if($data['express_price']>0){
            $content .= '配送费用：+￥'.$data['express_price'].'<BR>';
        }
        if($data['pack_price']>0){
            $content .= '餐盒费用：+￥'.$data['pack_price'].'<BR>';
        }
        if($data['ware_price']>0){
            $content .= '餐具调料：+￥'.$data['ware_price'].'<BR>';
        }
        if($data['activity_price']>0){
            $content .= '优惠金额：-￥'.$data['activity_price'].'<BR>';
        }
        $content .= '实付金额：￥'.$data['pay_price'].'<BR>';
        if($data['flavor']){
            $content .= '口味要求：'.$data['flavor'].'<BR>';
        }
        if($data['message']){
            $content .= '顾客留言：'.$data['message'].'<BR>';
        }
        if($data['order_mode']['value']==20){
            $content .= '配送地址：'.$data['address']['detail'].'<BR>';
            $content .= '接 收 人：'.$data['address']['name'].$data['address']['phone'].'<BR>';
        }
        $content .= '<CB># '.$title.' # 完</CB><BR>';
        $content .= '<BR><BR><CUT>';
        return $content;
    }
    
    /**
     * 制作退单模板
     * $data 退单数据
     * 58mm的机器,一行打印16个汉字,32个字母;
     */
    private function make_refund_templet($data)
    {
        if($data['order_mode']['value']==10){
            if(isset($data['table']['table_name'])){
                $title = $data['table']['table_name'];
            }else{
                $title = '堂食'.$data['row_no'].'号';
            }
        }
        if($data['order_mode']['value']==20){
            $title = '外卖'.$data['row_no'].'号';
        }
        if($data['order_mode']['value']==30){
            $title = '自取'.$data['row_no'].'号';
        }
        $content = '<CB># 退单 #</CB><BR>';
        $content .= '<CB>- '.$title.' -</CB><BR>';
        $content .= '--------------------------------<BR>';
        $content .= '<C>'.$data['shop']['shop_name'].'</C><BR>';
        $content .= '<B>名称        数量</B><BR>';//字符占位数量4+8+4
        $content .= '--------------------------------<BR>';
        //循环拼接打印模板
        for ($i = 0; $i < sizeof($data['goods']); $i++) {
            if($data['goods'][$i]['refund_num']>0){
                $goods_name = $data['goods'][$i]['goods_name'];//产品名字
                !empty($data['goods'][$i]['goods_attr']) && $goods_name .= "/" . $data['goods'][$i]['goods_attr'];
                $refund_num = $data['goods'][$i]['refund_num']; //产品数量
                //设置名称字符长度
                $lan = mb_strlen($goods_name,'utf-8')*2;//一个汉字2个字符长度
                for($n=$lan;$n<13;$n++){
                    $goods_name .= ' ';
                }
                $content .= '<B>' . $goods_name . '×' . $refund_num . '</B><BR>';
            }
        }
        $content .= '--------------------------------<BR>';     
        $content .= '付款金额：￥'.$data['pay_price'].'<BR>';
        $content .= '退款金额：￥'.$data['refund_price'].'<BR>';
        $content .= '退款理由：'.$data['refund_desc'].'<BR>';
        $content .= '<CB># 退单 # 完</CB><BR>';
        $content .= '<BR><BR><CUT>';
        return $content;
    }

}
